package drds.server.execute_engine.data_handling.tmp;

import java.util.Comparator;

import drds.server.execute_engine.data_handling.OrderByColum;
import drds.server.execute_engine.data_handling.RowDataPacketSorter;
import drds.server.net.packet.RowDataPacket;

public class RowDataComparator implements Comparator<RowDataPacket> {

	private OrderByColum[] orderByColums;

	public RowDataComparator(OrderByColum[] orderByColums) {
		this.orderByColums = orderByColums;
	}

	@Override
	public int compare(RowDataPacket $1, RowDataPacket $2) {
		OrderByColum[] orderByColums = this.orderByColums;
		int result = 0;
		int length = orderByColums.length;
		// 依次比较order by语句上的多个排序字段的值
		int orderByType = OrderByColum.ORDER_TYPE_ASC;
		for (int i = 0; i < length; i++) {
			int columIndex = orderByColums[i].colum.columIndex;
			byte[] left = $1.fieldBytesList.get(columIndex);
			byte[] right = $2.fieldBytesList.get(columIndex);
			if (orderByColums[i].orderType == orderByType) {
				result = RowDataPacketSorter.compareObject(left, right, orderByColums[i]);
			} else {
				result = RowDataPacketSorter.compareObject(right, left, orderByColums[i]);
			}
			if (result != 0) {
				return result;
			}
		}
		return result;
	}

}
